package com.weds.frame.core.runner;

import com.weds.frame.core.constant.CoreConstant;
import com.weds.frame.core.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.stereotype.Component;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2023/3/23 08:54
 */
@Component
@ConditionalOnProperty(name = "rpc.active", matchIfMissing = false, havingValue = "true")
@ComponentScans(value = {@ComponentScan("com.weds.frame.core.runner.schedule"), @ComponentScan("com.weds.frame.core.runner.rpc")})
@Slf4j
public class CommonRunner implements ApplicationRunner {

    @Value("${spring.application.name}")
    private String applicationName;

    @Value("${customer-server.addr}")
    private String serverAddr;

    @Value("${schedule.mode}")
    private String scheduleMode;

    @Value("${customer-server.protocol}")
    private String protocol;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${server.port}")
    private String port;

    @Autowired
    private RedisUtil redis;


    @Override
    public void run(ApplicationArguments args) {
        try {
            initServerToRedis();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            log.info("注册服务到redis成功");
        }
    }

    private void initServerToRedis() {
        String addr = protocol + "://" + serverAddr + ":";
        String redisKey = CoreConstant.REDIS_ADDR_SERVER + ":" + applicationName;
        // 单机模式，每次启动都会刷新key
        if (scheduleMode.equals("standAlone")) {
            redis.put(redisKey,addr + port + contextPath);
//            Map<String,Object> paramMap = new HashMap<>();
//            paramMap.put("1",addr + port + contextPath);
//            redis.setCacheMap(redisKey,paramMap);
        }
        // todo 集群模式
    }
}
